package com.ny.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String fromEmail;

    // 存储验证码的Map，实际项目中应该使用Redis等缓存
    private Map<String, String> verificationCodes = new HashMap<>();

    /**
     * 生成随机验证码
     *
     * @return 四位数字验证码
     */
    public String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 发送验证码到指定邮箱
     *
     * @param toEmail 接收验证码的邮箱地址
     * @return 生成的验证码
     */
    public String sendVerificationCode(String toEmail) {
        String code = generateVerificationCode();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(toEmail);
        message.setSubject("密码修改验证码");
        message.setText("您正在通过邮箱修改密码，验证码为：" + code + "，有效时间为5分钟。");

        mailSender.send(message);

        // 将验证码存储到Map中，实际项目中应该设置过期时间
        verificationCodes.put(toEmail, code);
        
        return code;
    }

    /**
     * 验证验证码是否正确
     *
     * @param email 邮箱地址
     * @param code  验证码
     * @return 验证结果
     */
    public boolean verifyCode(String email, String code) {
        String storedCode = verificationCodes.get(email);
        if (storedCode == null) {
            return false;
        }
        return storedCode.equals(code);
    }

    /**
     * 移除已使用的验证码
     *
     * @param email 邮箱地址
     */
    public void removeCode(String email) {
        verificationCodes.remove(email);
    }
}